<template>
  <div class="rescue-container">
    <!-- 顶部控制栏 -->
    <div class="control-bar">
      <el-button size="small" type="danger" circle>
        <i class="icon el-icon-bell"></i>
      </el-button>
      
      <div class="patient-info">
        <span class="patient-id">908</span>
        <span class="patient-name">吾*英</span>
        <span class="patient-age">41岁</span>
      </div>
      
      <div class="time-control">
        <span>抢救开始时间:</span>
        <el-date-picker
          v-model="rescueStartTime"
          type="datetime"
          placeholder="选择时间"
          :disabled="isRescuing"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
        />
        
        <span>采集频率:</span>
        <el-select 
          v-model="collectionFrequency" 
          placeholder="请选择" 
          style="width: 100px;"
          :disabled="!isRescuing"
          @change="handleFrequencyChange"
        >
          <el-option label="1秒" value="1" />
          <el-option label="10秒" value="10" />
          <el-option label="30秒" value="30" />
          <el-option label="1分钟" value="60" />
          <el-option label="5分钟" value="300" />
        </el-select>
        <span>/次</span>
        
        <span class="timer" :style="{color: isRescuing ? '#FF0000' : '#999'}">
          {{ currentTime }}
        </span>
      </div>
      
      <div class="action-buttons">
        <el-button 
          size="small" 
          :type="isRescuing ? 'primary' : 'danger'" 
          @click="toggleRescueMode"
        >
          <i class="icon" :class="isRescuing ? 'el-icon-video-pause' : 'el-icon-video-play'"></i>
          {{ isRescuing ? '退出抢救' : '抢救开始' }}
        </el-button>
        <el-button size="small" class="history-btn">历史记录</el-button>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧趋势图 -->
      <div class="chart-area" style="border: 1px solid red;">
        <div class="chart-title">趋势图</div>
        <div class="chart-container" ref="chartContainer"></div>
        <div class="time-axis">
          <span v-for="time in timePoints" :key="time">{{ time }}</span>
        </div>
      </div>
      
      <!-- 右侧生命体征 -->
      <div class="vital-signs">
        <div class="vital-card" v-for="item in vitalSigns" :key="item.name">
          <div class="vital-name">{{ item.name }}</div>
          <div class="vital-value" :style="{color: item.color}">
            {{ item.value }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作区 -->
    <div class="operation-area">
      <!-- 措施按钮区 -->
      <div class="action-buttons">
        <div class="button-group">
          <div class="group-title">措施</div>
          <el-button 
            v-for="action in emergencyActions" 
            :key="action" 
            size="small" 
            @click="addActionRecord(action)"
          >
            {{ action }}
          </el-button>
        </div>
        
        <div class="button-group">
          <div class="group-title">用药</div>
          <el-button 
            v-for="med in medications" 
            :key="med" 
            size="small" 
            @click="addMedicationRecord(med)"
          >
            {{ med }}
          </el-button>
        </div>
      </div>
      
      <!-- 操作记录区 -->
      <div class="record-area">
        <div class="record-title">操作记录</div>
        <div class="record-form">
          <el-input
            v-model="operationNote"
            placeholder="请输入操作记录"
            size="small"
          ></el-input>
          <el-button 
            size="small" 
            type="primary" 
            @click="addOperationRecord"
          >新增</el-button>
        </div>
        
        <div class="records-list">
          <div class="record-header">
            <span>时间</span>
            <span>项目</span>
          </div>
          <div 
            v-for="(record, index) in operationRecords" 
            :key="index" 
            class="record-item"
            @click="editRecord(index)"
          >
            <span class="record-time">{{ record.time }}</span>
            <span class="record-action">{{ record.action }}</span>
          </div>
          <div v-if="operationRecords.length === 0" class="empty-record">
            暂无记录
          </div>
        </div>
      </div>
    </div>
    
    <!-- 退出确认对话框 -->
    <el-dialog
      title="提示"
      v-model:visible="confirmDialogVisible"
      width="30%"
    >
      <span>是否退出抢救模式?</span>
      <template v-slot:footer>
<span  class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">否</el-button>
        <el-button type="primary" @click="stopRescue">是</el-button>
      </span>
</template>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { formatTime } from '@/utils/format'

export default {
  name: 'RescueMonitor',
  data() {
    return {
      isRescuing: false,
      rescueStartTime: '',
      currentTime: '00:00:00',
      collectionFrequency: '60', // 默认1分钟
      confirmDialogVisible: false,
      operationNote: '',
      operationRecords: [],
      editingIndex: -1,
      vitalSigns: [
        { name: 'HR', value: '--', color: '#FF5252' },
        { name: 'RR', value: '--', color: '#4CAF50' },
        { name: 'SPO2', value: '--', color: '#2196F3' },
        { name: 'ibpS', value: '--', color: '#9C27B0' },
        { name: 'ibpD', value: '--', color: '#FF9800' },
        { name: 'NibpS', value: '--', color: '#607D8B' },
        { name: 'NibpD', value: '--', color: '#795548' }
      ],
      emergencyActions: [
        '胸外按压', '电除颤', '气管插管', '气管切开', 
        '动脉穿刺', '静脉穿刺', '心包穿刺', '腹腔穿刺',
        '关节穿刺', '吸痰', '洗胃', '灌肠', '紧急开胸', '紧急开腹'
      ],
      medications: [],
      timePoints: [
        '16:05', '16:10', '16:15', '16:20', '16:25', '16:30',
        '16:35', '16:40', '16:45', '16:50', '16:55', '17:00',
        '17:05', '17:10', '17:15', '17:20', '17:25', '17:30',
        '17:35', '17:40'
      ],
      chart: null,
      timer: null,
      mqttClient: null,
      dataUpdateInterval: null
    }
  },
  mounted() {
    this.initChart()
    this.initMQTT()
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose()
    }
    if (this.mqttClient) {
      this.mqttClient.end()
    }
    clearInterval(this.timer)
    clearInterval(this.dataUpdateInterval)
  },
  methods: {
    initChart() {
        console.log('ddddddddd')
      this.chart = echarts.init(this.$refs.chartContainer)
      this.updateChart()
    },
    
    updateChart() {
      const option = {
        grid: {
          top: 20,
          right: 10,
          bottom: 30,
          left: 50
        },
        //图例显示
        //   legend: {
        //   data: ['HR', 'RR', 'SPO2', 'ibpS', 'ibpD', 'NibpS', 'NibpD'], // 需要与series中的name一一对应
        //   right: 10, // 距离右侧距离
        //   top: 0, // 距离顶部距离
        //   itemGap: 20 // 图例间隔
        // },
        xAxis: {
          type: 'category',
          data: this.timePoints,
          axisLine: { lineStyle: { color: '#999' } }
        },
        yAxis: { 
          type: 'value', 
          splitLine: { lineStyle: { type: 'dashed' } } 
        },
        series: [
          {
            name: 'HR',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#FF5252', width: 2 },
            symbol: 'none'
          },
          {
            name: 'RR',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#4CAF50', width: 2 },
            symbol: 'none'
          },
          {
            name: 'SPO2',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#2196F3', width: 2 },
            symbol: 'none'
          },
          {
            name: 'ibpS',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#9C27B0', width: 2 },
            symbol: 'none'
          },
          {
            name: 'ibpD',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#FF9800', width: 2 },
            symbol: 'none'
          },
          {
            name: 'NibpS',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#607D8B', width: 2 },
            symbol: 'none'
          },
          {
            name: 'NibpD',
            type: 'line',
            data: Array(20).fill(0),
            smooth: true,
            lineStyle: { color: '#795548', width: 2 },
            symbol: 'none'
          }
        ]
      }
      this.chart.setOption(option)
    },
    
    initMQTT() {
      // 模拟MQTT连接，实际项目中替换为真实MQTT客户端
      this.mqttClient = {
        onMessage: (callback) => {
          this.dataUpdateInterval = setInterval(() => {
            if (this.isRescuing) {
              const data = {
                HR: Math.floor(60 + Math.random() * 40),
                RR: Math.floor(12 + Math.random() * 10),
                SPO2: Math.floor(90 + Math.random() * 10),
                ibpS: Math.floor(100 + Math.random() * 40),
                ibpD: Math.floor(60 + Math.random() * 20),
                NibpS: Math.floor(110 + Math.random() * 30),
                NibpD: Math.floor(70 + Math.random() * 20)
              }
              console.log('data',data);
         
              callback(data)
            }
          }, 10000) // 每10秒更新一次数据
        }
      }
      
      this.mqttClient.onMessage((data) => {
        this.updateVitalSigns(data)
        this.updateChartData(data)
      })
    },
    
    updateVitalSigns(data) {
      this.vitalSigns.forEach(item => {
        if (data[item.name] !== undefined) {
          item.value = data[item.name]
        }
      })
    },
    
    updateChartData(data) {
      const option = this.chart.getOption()
      
      // 更新系列数据
      option.series.forEach(series => {
        // 移除第一个数据点
        series.data.shift()
        // 添加新数据点
        const value = data[series.name] || 0
        series.data.push(value)
      })
      
      this.chart.setOption(option)
    },
    
    toggleRescueMode() {
      if (this.isRescuing) {
        this.confirmDialogVisible = true
      } else {
        this.startRescue()
      }
    },
    
    startRescue() {
      this.isRescuing = true
      this.rescueStartTime = formatTime(new Date(), 'HH:mm:ss')
      this.startTimer()
      
      // 清空图表数据
      const option = this.chart.getOption()
      option.series.forEach(series => {
        series.data = Array(20).fill(0)
      })
      this.chart.setOption(option)
      
      // 清空记录
      this.operationRecords = []
    },
    
    stopRescue() {
      this.isRescuing = false
      this.confirmDialogVisible = false
      clearInterval(this.timer)
      this.timer = null
      this.currentTime = '00:00:00'
      
      // 重置生命体征显示
      this.vitalSigns.forEach(item => {
        item.value = '--'
      })
    },
    
    startTimer() {
      let seconds = 0
      this.timer = setInterval(() => {
        seconds++
        const hrs = Math.floor(seconds / 3600).toString().padStart(2, '0')
        const mins = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0')
        const secs = (seconds % 60).toString().padStart(2, '0')
        this.currentTime = `${hrs}:${mins}:${secs}`
      }, 1000)
    },
    
    handleFrequencyChange() {
      // 根据新的采集频率调整图表更新频率
      clearInterval(this.dataUpdateInterval)
      this.initMQTT()
    },
    
    addActionRecord(action) {
      this.addOperationRecord({
        time: formatTime(new Date(), 'HH:mm:ss'),
        action: action
      })
    },
    
    addMedicationRecord(med) {
      this.addOperationRecord({
        time: formatTime(new Date(), 'HH:mm:ss'),
        action: `用药: ${med}`
      })
    },
    
    addOperationRecord(record) {
      if (!record) {
        if (!this.operationNote.trim()) return
        
        record = {
          time: formatTime(new Date(), 'HH:mm:ss'),
          action: this.operationNote
        }
      }
      
      if (this.editingIndex >= 0) {
        // 更新现有记录
        this.operationRecords.splice(this.editingIndex, 1, record)
        this.editingIndex = -1
      } else {
        // 新增记录
        this.operationRecords.unshift(record)
      }
      
      this.operationNote = ''
    },
    
    editRecord(index) {
      this.editingIndex = index
      this.operationNote = this.operationRecords[index].action
    }
  }
}
</script>

<style lang="scss" scoped>
.rescue-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 15px;
  background-color: #f5f7fa;
}

.control-bar {
  display: flex;
  align-items: center;
  background: white;
  padding: 10px 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  
  .patient-info {
    margin-left: 15px;
    font-weight: bold;
    
    .patient-id {
      color: #333;
      margin-right: 10px;
    }
    
    .patient-name {
      color: #1565C0;
      margin-right: 10px;
    }
    
    .patient-age {
      color: #666;
    }
  }
  
  .time-control {
    flex: 1;
    display: flex;
    align-items: center;
    margin-left: 30px;
    
    > * {
      margin-right: 10px;
    }
    
    .timer {
      font-family: 'Arial', sans-serif;
      font-size: 18px;
      font-weight: bold;
      min-width: 80px;
      color: #FF0000;
    }
  }
  
  .action-buttons {
    margin-left: auto;
    
    .history-btn {
      margin-left: 10px;
    }
  }
}

.main-content {
  display: flex;
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.chart-area {
  flex: 3;
  display: flex;
  flex-direction: column;
  
  .chart-title {
    font-weight: bold;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 300px;
    width: 100%;
  }
  
  .time-axis {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    font-size: 12px;
    color: #666;
  }
}

.vital-signs {
  flex: 1;
  padding-left: 20px;
  border-left: 1px solid #eee;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  align-content: start;
  
  .vital-card {
    background: #f9f9f9;
    border-radius: 4px;
    padding: 10px;
    text-align: center;
    
    .vital-name {
      color: #666;
      font-size: 14px;
      margin-bottom: 5px;
    }
    
    .vital-value {
      font-weight: bold;
      font-size: 18px;
    }
  }
}

.operation-area {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  
  .action-buttons {
    width: 300px;
    margin-right: 20px;
    
    .button-group {
      margin-bottom: 15px;
      
      .group-title {
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .el-button {
        margin-right: 5px;
        margin-bottom: 5px;
      }
    }
  }
  
  .record-area {
    flex: 1;
    
    .record-title {
      font-weight: bold;
      margin-bottom: 10px;
    }
    
    .record-form {
      display: flex;
      margin-bottom: 10px;
      
      .el-input {
        flex: 1;
        margin-right: 10px;
      }
    }
    
    .records-list {
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #eee;
      border-radius: 4px;
      
      .record-header {
        display: flex;
        padding: 5px 10px;
        background: #f5f5f5;
        font-weight: bold;
        border-bottom: 1px solid #eee;
        
        span {
          flex: 1;
        }
      }
      
      .record-item {
        display: flex;
        padding: 5px 10px;
        border-bottom: 1px solid #eee;
        cursor: pointer;
        
        &:hover {
          background-color: #f9f9f9;
        }
        
        .record-time {
          flex: 0 0 80px;
          color: #666;
        }
        
        .record-action {
          flex: 1;
        }
      }
      
      .empty-record {
        padding: 20px;
        text-align: center;
        color: #999;
      }
    }
  }
}
</style>